package com.gitee.lichoking.mysoap.convert;

import com.gitee.lichoking.mysoap.util.StringUtils;
import org.dom4j.Node;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.regex.Pattern;

/**
 * Date转换器
 *
 * @author lich
 * @date 2021/6/1
 */
public class DateConverter implements Converter<Date> {
    private static final Pattern DATE = Pattern.compile("^\\d{4}-\\d{1,2}-\\d{1,2}$");
    private static final Pattern DATE2 = Pattern.compile("^\\d{4}/\\d{1,2}/\\d{1,2}$");
    private static final Pattern DATE_TIME = Pattern.compile("^\\d{4}-\\d{1,2}-\\d{1,2} {1}\\d{1,2}:\\d{1,2}:\\d{1,2}$");
    private static final Pattern DATE_TIME2 = Pattern.compile("^\\d{4}/\\d{1,2}/\\d{1,2} {1}\\d{1,2}:\\d{1,2}:\\d{1,2}$");

    @Override
    public Date nodeTextToJavaData(Node node) {
        String text = node.getText();
        if (StringUtils.isEmpty(text)) {
            return null;
        }
        Date date = null;
        try {
            SimpleDateFormat sdf = null;
            if (DATE.matcher(text).matches()) {
                sdf = new SimpleDateFormat("yyyy-MM-dd");
                date = sdf.parse(text);
            } else if (DATE2.matcher(text).matches()) {
                sdf = new SimpleDateFormat("yyyy/MM/dd");
                date = sdf.parse(text);
            } else if (DATE_TIME.matcher(text).matches()) {
                sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                date = sdf.parse(text);
            } else if (DATE_TIME2.matcher(text).matches()) {
                sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
                date = sdf.parse(text);
            }
        } catch (ParseException e) {
            throw new ConverterException("日期解析失败" + text);
        }
        return date;
    }
}
